import auth from "@/api/auth";
import { usePermissionStore } from "@/stores/permission";
import router from "@/router";

const whiteList = ["/login", "/404"];

export default {
  install: (app, options) => {
    //匹配相应路径的所有文件
    const modules = import.meta.glob("../views/**/*.vue");
    // 路由进入之前检查登录信息
    router.beforeEach(async (to, from) => {
      if (to.path !== "/login") {
        // 调用后端接口检查登录状态
        const resp = await auth.getUserInfo();
        const userInfo = resp.data || {};
        // 如果用户信息不存在或未登录，重定向到登录页面
        if (!userInfo || !userInfo.isLogin) {
          if (!whiteList.includes(to.path)) {
            // console.log(to.fullPath);

            return { path: "/login", query: { redirect: to.fullPath } };
          }
        } else {
          const permissionStore = usePermissionStore();
          // 检查是否已加载路由信息
          if (permissionStore.asyncRoutes.length === 0) {
            await permissionStore.fetchAsyncRoutes();
            // 动态添加路由,先初始化路由
            permissionStore.asyncRoutes.forEach((route) => {
              // console.log(route);
              const importComponent =
                modules[`../views/${route.component}.vue`];
              // console.log(importComponent);
              router.addRoute("Layout", {
                ...route,
                component: importComponent,
                props: true,
              });
            });
            // 触发重定向
            return { path: to.path, query: to.query, hash: to.hash };
          }
        }
      }
    });
  },
};
